package com.meirengu.webview.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.meirengu.common.RedisClient;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.NumberUtil;
import com.meirengu.webview.dao.KwWxSubscribeDao;
import com.meirengu.webview.model.KwWxSubscribe;
import com.meirengu.webview.service.HyWxSubscribeService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Service
public class HyWxSubscribeServicelmpl extends BaseServiceImpl<KwWxSubscribe> implements HyWxSubscribeService {


    @Autowired
    RedisClient redisClient;

    @Autowired
    ProducerBean producer;

    @Autowired
    private KwWxSubscribeDao kwWxSubscribeDao;


    Logger logger = LoggerFactory.getLogger(YjWxSubscribeServiceImpl.class);


    public void wxAccessToken() throws Exception {
        String accessToken = "";
        /*HttpUtil.HttpResult hr = HttpUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6c09d7bf83d9b8f2&secret=3c6667228c17dd595f69dfb45d098d2b");*/
        HttpUtil.HttpResult hr = HttpUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx7d941f4fdddad1be&secret=135e18f4da8c4e566ada36299add43fc");
        int code = hr.getStatusCode();
        logger.info("hr:{}" + hr.toString());
        if (code == 200) {
            logger.info("==wxAccessToken http requesst success. result:{}", code, hr.toString());
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            accessToken = returnMsg.getString("access_token");
            redisClient.set("HYWXACCESSTOKEN", accessToken);
        } else {
            logger.warn("==wxAccessToken http requesst fail. code:{}, result:{}", code, hr.toString());
        }


    }

    public void createMenu() throws Exception {
        JSONObject jsonObject = new JSONObject();
        JSONArray button = new JSONArray();
        JSONObject button1 = new JSONObject();//我要贷款
        JSONObject button2 = new JSONObject();//帮你借
        JSONObject button3 = new JSONObject();//大额借款

        button1.put("type", "view");
        button1.put("name", "⚡秒下款");
        button1.put("url", "https://mdzj139.com/loan/index.html?cid=channel_wxtg6#/market");
        button.add(button1);

        button2.put("type", "view");
        button2.put("name", "\uD83D\uDCD6娇妻难宠");
        button2.put("url", "https://51klm.cn/#/book-read?bid=35&total_count=1");
        button.add(button2);

        button3.put("type", "view");
        button3.put("name", "\uD83D\uDD25大额借款");
        button3.put("url", "https://mdzj139.com/loan/?cid=channel_wxtg6");
        button.add(button3);
        jsonObject.put("button", button);


        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + redisClient.get("HYWXACCESSTOKEN");
        HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
        System.out.println(hr.toString());
    }

    public String getUserList(String openId) throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + redisClient.get("HYWXACCESSTOKEN");
        if (StringUtils.isNotBlank(openId)) {
            url = url + "&next_openid=" + openId;
        }
        /*String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=14_XtlAFIKufRItmgnngj9qi00aSvVEgANRktePBLaPct5jQ0okZpNY4IvZN5AQ1LqasQAeITrFAbKOp4upvySBq7KMbz8ETIhAOovNTY4YLPfSn3UWYkPR6cmXkbD822v0fnSuWsGQzt5nrO9aTSNbAEALKF";*/
        HttpUtil.HttpResult hr = HttpUtil.doGet(url);
        int code = hr.getStatusCode();
        String nextOpenId = "";
        if (code == 200) {
            logger.info("==getUserList http requesst success. result:{}", code, hr.toString());
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            JSONObject data = returnMsg.getJSONObject("data");
            JSONArray openidAry = data.getJSONArray("openid");
            nextOpenId = returnMsg.getString("next_openid");
            String toUserName = "gh_25e40b50f9b3";
            String openid = null;
            //校验是否已订阅
            Map<String, Object> params = new HashMap<>();
            Integer count = null;
            KwWxSubscribe kwWxSubscribe = null;
            System.out.println("快来红鱼" + hr.toString());
            for (int i = 0; i < openidAry.size(); i++) {
                openid = openidAry.getString(i);
                params.put("fromUserName", openid);
                params.put("toUserName", toUserName);
                count = kwWxSubscribeDao.getCount(params);
                //已有推送记录
                if (!NumberUtil.isNullOrZero(count)) {
                    System.out.println("已有订阅");
                    continue;
                }
                /*String userUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + redisClient.get("HGWXACCESSTOKEN") + "&openid=" + openid + "&lang=zh_CN";
                HttpUtil.HttpResult hr1 = HttpUtil.doGet(userUrl);
                String content1 = new String(hr1.getContent().getBytes("ISO-8859-1"),"UTF-8");
                logger.info("content1:{}"+content1);
                JSONObject jsonObject = JSONObject.parseObject(content1);
                String nikeName = jsonObject.getString("nickname");
                if(StringUtils.isBlank(nikeName)){
                    nikeName = "尊敬的用户";
                }*/
                kwWxSubscribe = new KwWxSubscribe();
                kwWxSubscribe.setToUserName(toUserName);
                kwWxSubscribe.setFromUserName(openid);
                kwWxSubscribe.setCreateTime(new Date());
                kwWxSubscribe.setMsgType("event");
                kwWxSubscribe.setEvent("subscribe");
                /*logger.info("nikeName:{}" + nikeName);
                kwWxSubscribe.setNikeName(nikeName);*/
                kwWxSubscribeDao.insert(kwWxSubscribe);
            }
        } else {
            logger.warn("==HYWXACCESSTOKEN http requesst fail. code:{}, result:{}", code, hr.toString());
        }
        return nextOpenId;
    }


    public void sendTemplateMsg(String name) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> map = new HashMap<>();
        map.put("toUserName", "gh_25e40b50f9b3");
        List<Map<String, Object>> userList = getList(map);
        String openid = null;
        JSONObject dataJson = null;
        JSONObject first = null;
        JSONObject keyword1 = null;
        JSONObject keyword2 = null;
        JSONObject keyword3 = null;
        JSONObject keyword4 = null;
        JSONObject keyword5 = null;
        JSONObject remark = null;
        int count = 0;
        for (Map<String, Object> userMap : userList) {
            logger.info("count========>. count:{}", count++);
            openid = userMap.get("fromUserName").toString();
            jsonObject.put("touser", openid);
            jsonObject.put("template_id", "NHT6TKgiqaoJhmOni7Ky-7vIZ0tyWNqmuMM5b37uw3c");
            jsonObject.put("url", "https://mdzj139.com/loan/index.html?cid=channel_wxtg6#/market");
            dataJson = new JSONObject();

            first = new JSONObject();
            first.put("value", "根据您的资质和情况，已符合贷款资格，额度10000-50000元");
            first.put("color", "#FF0000");
            dataJson.put("first", first);

            keyword1 = new JSONObject();
            keyword1.put("value", name);
            keyword1.put("color", "#173177");
            dataJson.put("keyword1", keyword1);

            keyword2 = new JSONObject();
            keyword2.put("value", sdf.format(new Date()));
            keyword2.put("color", "#173177");
            dataJson.put("keyword2", keyword2);

            keyword3 = new JSONObject();
            keyword3.put("value", "10000-50000");
            keyword3.put("color", "#173177");
            dataJson.put("keyword3", keyword3);

            keyword4 = new JSONObject();
            keyword4.put("value", "7-30天");
            keyword4.put("color", "#173177");
            dataJson.put("keyword4", keyword4);

            remark = new JSONObject();
            StringBuilder contentBuffer = new StringBuilder();
            contentBuffer.append("点击立即申请>>>");
            String contentStr = contentBuffer.toString();
            remark.put("value", contentStr);
            remark.put("color", "#FF0000");
            dataJson.put("remark", remark);

            jsonObject.put("data", dataJson);

            /*String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=14_DhgdYNoEVjs2ajDbFpyrDF9V-Xaaq9GLd_iGYgocAWs_LyCMw0fDnjmV5ItLcrhUlnNnRqjoPZVdqH3w2QA4pa2mumB9gFuE_GnHifgXm_qPO7iCBwc4gPqtRCsHGRx4vIFL4oHUAzT-bS0FMVOfADAVEX";*/
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + redisClient.get("HYWXACCESSTOKEN");
            HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
            System.out.println(hr.toString());
        }


    }

    public void sendTemplateMsgMultiple(String name) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Map<String, Object> map = new HashMap<>();
        map.put("toUserName", "gh_25e40b50f9b3");
        List<Map<String, Object>> userList = getList(map);
        Executor executor = Executors.newFixedThreadPool(30);//启用多线程
        for (Map<String, Object> userMap : userList) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String openid = null;
                        JSONObject jsonObject = new JSONObject();
                        JSONObject dataJson = null;
                        JSONObject first = null;
                        JSONObject keyword1 = null;
                        JSONObject keyword2 = null;
                        JSONObject keyword3 = null;
                        JSONObject keyword4 = null;
                        JSONObject keyword5 = null;
                        JSONObject remark = null;
                        openid = userMap.get("fromUserName").toString();
                        jsonObject.put("touser", openid);
                        jsonObject.put("template_id", "NHT6TKgiqaoJhmOni7Ky-7vIZ0tyWNqmuMM5b37uw3c");
                        jsonObject.put("url", "https://mdzj139.com/loan/index.html?cid=channel_wxtg6#/market");
                        dataJson = new JSONObject();

                        first = new JSONObject();
                        first.put("value", "根据您的资质和情况，已符合贷款资格，额度10000-50000元");
                        first.put("color", "#FF0000");
                        dataJson.put("first", first);

                        keyword1 = new JSONObject();
                        keyword1.put("value", name);
                        keyword1.put("color", "#173177");
                        dataJson.put("keyword1", keyword1);

                        keyword2 = new JSONObject();
                        keyword2.put("value", sdf.format(new Date()));
                        keyword2.put("color", "#173177");
                        dataJson.put("keyword2", keyword2);

                        keyword3 = new JSONObject();
                        keyword3.put("value", "10000-50000");
                        keyword3.put("color", "#173177");
                        dataJson.put("keyword3", keyword3);

                        keyword4 = new JSONObject();
                        keyword4.put("value", "7-30天");
                        keyword4.put("color", "#173177");
                        dataJson.put("keyword4", keyword4);

                        remark = new JSONObject();
                        StringBuilder contentBuffer = new StringBuilder();
                        contentBuffer.append("点击立即申请>>>");
                        String contentStr = contentBuffer.toString();
                        remark.put("value", contentStr);
                        remark.put("color", "#FF0000");
                        dataJson.put("remark", remark);

                        jsonObject.put("data", dataJson);

                        /*String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=14_DhgdYNoEVjs2ajDbFpyrDF9V-Xaaq9GLd_iGYgocAWs_LyCMw0fDnjmV5ItLcrhUlnNnRqjoPZVdqH3w2QA4pa2mumB9gFuE_GnHifgXm_qPO7iCBwc4gPqtRCsHGRx4vIFL4oHUAzT-bS0FMVOfADAVEX";*/
                        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + redisClient.get("HYWXACCESSTOKEN");
                        HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
                        System.out.println(hr.toString());
                    } catch (Exception e) {

                    }
                }
            });

        }

    }

}
